package com.zhouxiaoge.mongo.controller;

import com.zhouxiaoge.mongo.documents.User;
import com.zhouxiaoge.mongo.respository.UserRepository;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * @author 周小哥
 */
@Tag(name = "Mongo测试")
@RestController
public class MongoController {

    @Resource
    private UserRepository userRepository;

    @Operation(summary = "首页")
    @GetMapping("/")
    public ResponseEntity<String> index() {
        return ResponseEntity.ok("Hello, this is mongo ! ~ " + LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
    }

    @Operation(summary = "新增用户")
    @PostMapping("/add")
    public ResponseEntity<User> add(@RequestBody User user) {
        User save = userRepository.insert(user);
        return ResponseEntity.ok(save);
    }

    @Operation(summary = "分页查询")
    @Parameters({
            @Parameter(name = "pageSize", description = "每页大小"),
            @Parameter(name = "pageNumber", description = "页码")
    })
    @PostMapping("/query")
    public ResponseEntity<Page<User>> find(int pageSize, int pageNumber) {
        Sort id = Sort.by(Sort.Order.desc("id"));
        PageRequest pageRequest = PageRequest.of(pageNumber, pageSize).withSort(id);
        Page<User> all = userRepository.findAll(pageRequest);
        return ResponseEntity.ok(all);
    }
}
